<template>
 <!-- 评论区 -->
    <div class="comment_list" :class="isShowBox1 ? 'art-cmt-container-1' : 'art-cmt-container-2'">
    <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
    >
      <div class="con_list_item" :key="item.com_id" v-for="item in commentList">
        <div class="con_info">
         <div class="condetail">
            <img :src="item.aut_photo" alt="">
            <span>{{item.aut_name}}</span>
         </div>
          <div class="icon  " v-if="item.is_liking">  <van-icon name="like" size="24" color="red" @click="changeGray(item)" /><p>{{item.like_count}}</p></div>
           <div class="icon" v-else @click="changeRed(item)"> <van-icon name="like" size="24" color="gray" /><p>{{item.like_count}}</p></div>

        </div>
        <div class="con_body">
          <p>{{item.content}}</p>
        </div>
        <div class="con_foot">
          <p>{{item.pubdate | dateFormat}}</p>
        </div>
      </div>
     </van-list>

     <!-- 底部添加评论区域 - 1 -->
<div class="add-cmt-box van-hairline--top"  v-if="isShowBox1">
  <van-icon name="arrow-left" size="18" @click="$router.back()" />
  <div class="ipt-cmt-div" @click="showBox2">发表评论</div>
  <div class="icon-box">
    <van-badge :content= total_count :max="99">
      <van-icon name="comment-o" size="20" @click="scrollToCmtList" />
    </van-badge>
    <van-icon name="star-o" size="20" />
    <van-icon name="share-o" size="20" />
  </div>
</div>

<!-- 底部添加评论区域 - 2 -->
<div class="cmt-box van-hairline--top" v-else>
  <textarea placeholder="友善评论、理性发言、阳光心灵" @blur="hideBox2" ref="textarea" v-model="cmt" ></textarea>
  <van-button type="default" :disabled="cmt.length===0" @click="pubCmt">发布</van-button>
</div>
    </div>

</template>

<script>
import { getComment, upCommentLike, cannelCommentLike, pubComment } from '../API/commentAPI.js'
import { animate } from 'popmotion'
export default {
  props: ['artId', 'cmtSum'],
  data () {
    return {
      // 判断是否加载完数据
      finished: false,
      // 判断是否在加载中，如果为true，表明正在加载中，如果为false，说明加载完毕
      loading: false,
      commentList: [],
      lastId: null,
      isShowBox1: true,
      total_count: 0,
      cmt: '',
      Ucomment: null
    }
  },
  methods: {
    // 获取评论数据
    async getCommentData () {
      const { data: res } = await getComment('a', this.artId, this.lastId)
      this.total_count = res.data.total_count
      if (res.message === 'OK') {
        this.commentList = [...this.commentList, ...res.data.results]
        this.lastId = res.data.last_id
        this.loading = false
      }
      if (res.data.results.length === 0) {
        this.finished = true
      }
    },
    async changeRed (item) {
      const { data: res } = await upCommentLike(item.com_id)
      if (res.message === 'OK') {
        item.is_liking = true
        item.like_count += 1
        this.getCommentData()
        this.$toast.success('点赞成功！')
      }
      console.log(res)
    },

    async changeGray (item) {
      const data = await cannelCommentLike()
      if (data.status === 204) {
        item.is_liking = false
        item.like_count -= 1
        this.getCommentData()
        this.$toast.success('取消点赞成功！')
      }
    },
    onLoad () {
      console.log('加载成功')
      this.getCommentData()
    },
    showBox2 () {
      this.isShowBox1 = false
      // 1. 将回调函数延迟到下次 DOM 更新完毕之后执行
      this.$nextTick(() => {
        // 2. 通过 ref 获取到 textarea 的引用
        this.$refs.textarea.focus()
      })
    },
    hideBox2 () {
      // 当文本框失去焦点时，延迟 100ms 再隐藏第二个评论区域
      // 目的：让发布评论的按钮能正常响应用户的点击事件
      setTimeout(() => {
        this.isShowBox1 = true
      }, 100)
    },
    // 发表评论
    async  pubCmt () {
      const state = localStorage.getItem('state')

      if (state) {
        const { data: res } = await pubComment(this.artId, this.cmt)

        if (res.message === 'OK') {
        // 评论数自增 +1

          this.cmtCount += 1
          // 将接口返回的、最新的评论内容，unshift 追加到 cmtlist 中
          this.commentList.unshift(res.data.new_obj)
          this.$toast.success('发表评论成功')
          this.cmt = ''
        }
      } else {
        const navPath = '/article/' + this.artId

        this.$router.replace('/login?pre=' + navPath)
      }
    },
    // 评论发表动画效果
    scrollToCmtList () {
      // 1. 当前滚动条的位置
      const now = window.scrollY
      // 2. 目标位置（文章信息区域的高度）
      const dist = document.querySelector('.article-container').offsetHeight

      // 3. 实现滚动动画
      animate({
        from: now, // 当前的位置
        to: dist, // 目标位置
        onUpdate: latest => window.scrollTo(10, latest)
      })
    }
  },
  created () {
    this.getCommentData()
  },
  watch: {
    artId () {
      this.commentList = []
      this.getCommentData()
    }
  }
}
</script>

<style lang="less" scoped>
.comment_list{
  width: 100%;

  .con_list_item{
    display: flex;
    flex-direction: column;
    padding: .288rem ;
    .con_info{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .red{
        color: red;

      }
      p{
        text-align: center;
        font-size: 0.3784rem;
        color: #999;
        word-break: break-all;
      }
      .condetail{
        display: flex;
        align-items: center;
        img{
            width: 1.06667rem;
            height: 1.06667rem;
            background-color: #f8f8f8;
            border-radius: 50%;
            margin-right: 0.4rem;
        }
        span{
            font-size: .32rem;
        }
      }
    }
    .con_body{
      color: #000;
      font-size: 0.4405rem;
      padding: 0.3243rem 20px;
      p{
        word-break: break-all;
      }
    }
    .con_foot{
      color: #666;
      font-size: 0.3405rem;
    }
  }

}

// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    margin-left: 10px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}
</style>
